from PIL import Image  
  
def rgb888_to_rgb565(r, g, b):  
    """Convert 8-bit RGB to 16-bit RGB565."""  
    r = r >> 3  # Red channel: 8 bits -> 5 bits  
    g = g >> 2  # Green channel: 8 bits -> 6 bits  
    b = b >> 3  # Blue channel: 8 bits -> 5 bits  
    return (r << 11) | (g << 5) | b  
  
def generate_c_array(image_path):  
    img = Image.open(image_path)  
    img = img.convert("RGB")  
  
    pixels = []  
    for y in range(img.height):  
        for x in range(img.width):  
            r, g, b = img.getpixel((x, y))  
            rgb565 = rgb888_to_rgb565(r, g, b)  
            pixels.append(f"0x{rgb565:04X}")  # Format as 4-digit hex with 0x prefix  
  
    # Create a C-style array initialization string  
    array_str = "const uint16_t pixels[] = {\n"  
    for i, pixel in enumerate(pixels):  
        array_str += f"    {pixel},"  
        if (i + 1) % 10 == 0:  # For example, add a newline after every 10 elements  
            array_str += "\n"  
    array_str += "\n};\n"  
  
    return array_str  
  



if __name__ == '__main__':
    img_file = open("img.h", "w")
    c_array = generate_c_array("image/1.png")  
    img_file.write(c_array)
    img_file.close()
    print(c_array)  
